import { ref } from 'vue'
import animations from 'create-keyframe-animation'

function useAnimation() {
  const cdWrapper = ref(null)
  let isEntering = false
  let isLeaving = false

  function enter(el, done) {
    isEntering = true
    if (isLeaving) {
      afterLeave()
    }
    const { x, y, scale } = getPosAndScale()
    const animation = {
      0: {
        transform: `translate3d(${x}px, ${y}px, 0) scale(${scale})`
      },
      100: {
        transform: 'translate3d(-50%,0,0) scale(1)'
      }
    }
    animations.registerAnimation({
      name: 'move',
      animation,
      presets: {
        duration: 600,
        easing: 'linear'
      }
    })
    animations.runAnimation(cdWrapper.value, 'move', done)
  }

  function afterEnter() {
    isEntering = false
    animations.unregisterAnimation('move')
    cdWrapper.value.style.animation = ''
  }

  function leave(el, done) {
    isLeaving = true
    if (isEntering) {
      afterEnter()
    }
    const { x, y, scale } = getPosAndScale()
    const dom = cdWrapper.value

    dom.style.transform = `translate3d(${x}px, ${y}px, 0) scale(${scale})`
    dom.style.transition = 'all 0.6s linear'
    dom.addEventListener('transitionend', callback)

    function callback() {
      done()
      dom.removeEventListener('transitionend', callback)
    }
  }

  function afterLeave() {
    isLeaving = false
    const dom = cdWrapper.value
    dom.style.transform = ''
    dom.style.transition = ''
  }

  function getPosAndScale() {
    const miniPlayerPaddingLeft = 20
    const miniPlayerHeight = 60
    const bigCdWidth = window.innerWidth * 0.8
    const littleCdWidth = 40
    const titleHeightAndMargin = 40 + 14 + 25
    // const x = -(window.innerWidth - miniPlayerPaddingLeft - littleCdWidth / 2)
    const x = -(
      window.innerWidth / 2 +
      bigCdWidth / 2 -
      miniPlayerPaddingLeft -
      littleCdWidth / 2
    )
    const y =
      window.innerHeight -
      titleHeightAndMargin -
      bigCdWidth / 2 -
      miniPlayerHeight / 2
    const scale = littleCdWidth / bigCdWidth

    return {
      x,
      y,
      scale
    }
  }

  return {
    cdWrapper,
    enter,
    afterEnter,
    leave,
    afterLeave
  }
}

export default useAnimation
